<template>
  <div class="loadHomeWork">
    <div class="loadHomeWorkIneer" v-if="showIndex">
      <div class="loadTop">设备证书 {{ shipDetailType }}</div>
      <div class="loadAndSearch">
        <div class="loadExcel">
          <div class="button" type="success" @click="uploadFile()">导入</div>
          <div class="button" type="success" @click="getExcelFile()">导出</div>
          <div class="button" type="success" @click="addOne()">新增</div>
          <div class="multiButton" type="success" @click="deleteMulti()">
            删除
          </div>
          <div class="buttonBack" @click="backIndexPage()">返回</div>
        </div>
        <div class="search" style="width: 260px !important">
          <input
            type="text"
            placeholder="证书名称"
            v-model="searchName"
            style="width: 200px !important"
          />
          <div class="searchButton" @click="getRenderList()">搜索</div>
        </div>
      </div>

      <div class="table" :style="{ width: tableWidth }">
        <el-table
          :header-cell-style="{
            background: '#FAFAFA',
            color: '#777676 !important',
            fontWeight: '800',
          }"
          :data="tableData"
          empty-text="暂无数据"
          border
          stripe
          style="width: 100%; height: auto"
          max-height="65vh"
          @selection-change="selecttableFunction"
          @sort-change="sortChange"
          @row-dblclick="handleRowDblclick"
          :row-style="{ height: 30 + 'px' }"
          :cell-style="{ padding: 0 + 'px' }"
          ><el-table-column type="selection" width="35" align="center" />
          <el-table-column
            type="index"
            :index="indexNumber"
            align="center"
            label="序号"
            min-width="55"
          >
          </el-table-column>

          <el-table-column
            prop="name"
            label="证书名称"
            align="center"
            min-width="400"
            show-overflow-tooltip
            sortable="custom"
          >
          </el-table-column>

          <el-table-column
            prop="number"
            label="证书编号"
            align="center"
            min-width="120"
          >
            <!-- <template #default="scope">
              <div class="LeftTexT">{{ scope.row.number }}</div>
            </template> -->
          </el-table-column>
          <el-table-column label="附件" width="55" prop="file" align="center">
            <template #default="{ row }">
              <div
                style="color: #67c23a; font-weight: 600"
                @click="showDetileFile(row)"
              >
                {{ showXiQIng(row.file) }}
              </div>
            </template>
          </el-table-column>
          <el-table-column
            prop="issueDate"
            label="签发日期"
            min-width="110"
            align="center"
          >
          </el-table-column>

          <el-table-column
            label="签注日期"
            min-width="110"
            prop="visaDate"
            align="center"
            :formatter="formatDate"
          />

          <el-table-column
            label="有效期至"
            min-width="110"
            prop="limitedTerm"
            align="center"
            :formatter="formatDate"
            sortable="custom"
          />
          <el-table-column
            label="签发单位"
            min-width="110"
            prop="issuingUnit"
            align="center"
          />
          <el-table-column
            label="备注"
            min-width="240"
            prop="remark"
            align="center"
          />
        </el-table>
        <!-- 内容过多，会出现滚动条 -->
      </div>
      <div class="foot">
        <div class="currentPage">当前第{{ page }}/{{ totalPages }}页</div>
        <div
          class="lastPage"
          :style="{ background: color }"
          @click="clickLastPage()"
        >
          上一页
        </div>
        <div
          class="nextPage"
          :style="{ backgroundColor: color1 }"
          @click="clickNextPage()"
        >
          下一页
        </div>
        <div class="currentNumber">共{{ totalNumber }}条</div>
        <div>跳转至:</div>
        <input
          type="text"
          class="skipPage"
          style="width: 50px !important"
          v-model="shipPageNumer"
        />
        <div class="sureSkip" @click="skipPage">确定</div>
      </div>
    </div>
    <div class="dialog" ref="dialog" :style="{ display: show }">
      <div class="loadHomeWorkIneer">
        <div class="changeTop">
          <div
            class="delete"
            @click="deleteOne(id)"
            v-show="addOrEdit == '编辑'"
          >
            删除
          </div>
          <div class="sure" @click="sureAdd()">确认</div>
          <div class="back" @click="backToIndex()">返回</div>
        </div>
        <div class="dialogText">{{ addOrEdit }}</div>
        <div class="manyInput">
          <div class="iuptInnerContain">
            <div class="inputInner">
              <div class="name">证书名称:</div>
              <input type="text" placeholder="证书名称" v-model="name" />
            </div>
            <div class="inputInner">
              <div class="name">证书编号:</div>
              <input type="text" placeholder="证书编号" v-model="number" />
            </div>

            <div class="inputInner">
              <div class="name">签发时间:</div>
              <div class="inputContainer">
                <el-config-provider :locale="locale">
                  <el-date-picker
                    v-model="issueDate"
                    type="date"
                    placeholder="签发时间"
                    format="YYYY/MM/DD"
                    value-format="YYYY/MM/DD"
                    @change="handleStartDateChange"
                  />
                </el-config-provider>
              </div>
            </div>
            <div class="inputInner">
              <div class="name">签注时间:</div>
              <div class="inputContainer">
                <el-config-provider :locale="locale">
                  <el-date-picker
                    v-model="visaDate"
                    type="date"
                    placeholder="签注时间"
                    format="YYYY/MM/DD"
                    value-format="YYYY/MM/DD"
                  />
                </el-config-provider>
              </div>
            </div>

            <div class="inputInner">
              <div class="name">有效期至:</div>
              <div class="inputContainer">
                <el-config-provider :locale="locale">
                  <el-date-picker
                    v-model="limitedTerm"
                    type="date"
                    placeholder="有效期至"
                    format="YYYY/MM/DD"
                    value-format="YYYY/MM/DD"
                    :picker-options="endPickerOptions"
                    @change="handleEndDateChange"
                  />
                </el-config-provider>
              </div>
            </div>
            <div class="inputInner">
              <div class="name">签发单位:</div>
              <input type="text" placeholder="签发单位" v-model="issuingUnit" />
            </div>
            <div class="inputInner">
              <div class="name">备注:</div>
              <input type="text" placeholder="格式" v-model="remark" />
            </div>
            <div class="seeCate">附件</div>
            <div class="seeCateTable">
              <el-table
                :header-cell-style="{
                  background: '#FAFAFA',
                  color: '#777676 !important',
                  fontWeight: '800',
                  height: '20px',
                }"
                empty-text="暂无数据"
                :row-style="{ height: 36 + 'px' }"
                :cell-style="{ padding: 0 + 'px' }"
                :data="upFileList"
                ref="leftTable"
                border
                @row-click="handleRowClick"
                highlight-current-row
                style="width: 100%; height: auto"
                max-height="200px"
              >
                <el-table-column
                  prop="name"
                  align="center"
                  label="附件详情"
                ></el-table-column>
                <el-table-column
                  fixed="right"
                  align="center"
                  label="操作"
                  width="140"
                >
                  <template #default="scope">
                    <div
                      style="
                        display: flex;
                        align-items: center;
                        justify-content: space-around;
                      "
                    >
                      <div
                        class="editText"
                        @click="changeFile(scope.row.url, scope.row.name)"
                      >
                        更改
                      </div>
                      <div
                        class="editText1"
                        @click="clickDeleteFile(scope.row.url, scope.row.name)"
                      >
                        删除
                      </div>
                    </div>
                  </template>
                </el-table-column>
              </el-table>
              <div class="addNewFile" style="margin-top: 100px">
                <el-button type="success" @click="editAddnewFile"
                  >新增附件</el-button
                >
              </div>
            </div>
          </div>
          <div class="pictureContainner">
            <img
              v-show="rightShowFlag == 'png' && src"
              width="100%"
              :src="src"
              alt=""
            />
            <iframe
              v-show="rightShowFlag == 'pdf' && src"
              :src="src"
              width="100%"
              height="600px"
            ></iframe>
          </div>
        </div>
      </div>
    </div>

    <div class="dialog2" :style="{ display: uploadfile }">
      <div class="upContain">
        <input
          type="file"
          ref="clearFile"
          class="addfile"
          @change="getFile($event)"
          accept=".xls,.xlsx"
        />
      </div>
      <div class="fileName">
        <div v-show="fileName">文件名:{{ fileName }}</div>
      </div>
      <div class="upFileSrue">
        <button class="buttonUpdata" @click="cancelUp()">取消</button>
        <button class="buttonUpdata buttonUpdata1" @click="submitAddFile()">
          确定
        </button>
      </div>
    </div>
    <div class="dialog3 dialog6" :style="{ display: uploadfile1 }">
      <div class="upContain">
        <input
          type="file"
          ref="clearFile"
          id="addfile"
          @change="getFile1($event)"
          style="text-indent: 0px"
        />
      </div>
      <div class="fileName">
        <div v-show="fileName1">{{ fileName1 }}</div>
      </div>
      <div class="upFileSrue">
        <button class="buttonUpdata" @click="cancelUp()">取消</button>
        <button class="buttonUpdata buttonUpdata1" @click="submitAddFile1()">
          确定
        </button>
      </div>
    </div>
    <div class="dialog4 dialog6" :style="{ display: changeFileUp }">
      <div class="changeFileContain">
        <div class="upContain">
          <input
            type="file"
            ref="clearFile"
            id="addfile"
            accept=".pdf,.PDF,.jpeg,.jpg,.png,.PNG"
            class="addfile1 addfile4"
            @change="getFile1($event)"
            style="text-indent: 0px"
          />
        </div>
        <div class="fileName">
          <div v-show="fileName1">{{ fileName1 }}</div>
        </div>
        <div class="upFileSrue">
          <button class="buttonUpdata" @click="cancelUp()">取消</button>
          <button class="buttonUpdata buttonUpdata1" @click="submitAddFile1()">
            确定
          </button>
        </div>
      </div>
    </div>
    <div class="dialog5" :style="{ display: showFile }">
      <div class="fileDetail">附件详情</div>
      <div class="showTable">
        <el-table
          empty-text="暂无数据"
          :header-cell-style="{
            background: '#FAFAFA',
            color: '#777676 !important',
            fontWeight: '800',
          }"
          :data="upFileList"
          border
          stripe
          style="width: 100%; height: auto"
          max-height="65vh"
        >
          <el-table-column
            prop="name"
            label="证书名称"
            align="center"
            min-width="200"
          />
          <el-table-column
            fixed="right"
            align="center"
            label="操作"
            width="140"
          >
            <template #default="scope">
              <div
                style="
                  display: flex;
                  align-items: center;
                  justify-content: space-around;
                "
              >
                <div class="editText2" @click="clickSeeFile(scope.row.url)">
                  查看
                </div>
                <div
                  class="editText2"
                  @click="clickDownLoadFile(scope.row.url, scope.row.name)"
                >
                  下载
                </div>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="coloseDialog5">
        <div class="coloseDialogButton" @click="closeDialog5">关闭</div>
      </div>
    </div>
  </div>
</template>

<script>
import EventBus from "@/mitt/eventBus.js";
import rename from "@/mitt/getPath.js";
import service from "@/api/api";
import _ from "lodash";
import zhCn from "element-plus/es/locale/lang/zh-cn";
import axios from "axios";
import sendClass from "@/mitt/sendClass";
export default {
  beforeRouteEnter(to, from, next) {
    sendClass(3, "设备证书");
    next();
  },
  name: "",
  data() {
    return {
      showIndex: true,
      compare: {},
      searchName: "",
      shipDetailType: "",
      shipPageNumer: 1,
      multi: [],
      totalNumber: 0,
      locale: zhCn,
      token: "",
      tableData: [],
      tableWidth: null,
      page: 1,

      size: 20,
      pageList: [],
      show: "none",
      addOrEdit: "新增",
      currentNum: 0,
      name: "",
      number: "",
      format: "",
      file: "",
      issueDate: "",
      visaDate: "",
      limitedTerm: "",
      issuingUnit: "",
      remark: "",
      id: "",
      totalPages: null,
      uploadfile: true,
      rightShowFlag: "png",
      src: null,
      data: {
        name: "",
        number: "",
        format: "",
        file: "",
        issueDate: "",
        visaDate: "",
        limitedTerm: "",
        issuingUnit: "",
        remark: "",
        type: "",
        id: "",
      },

      show1: "none",
      color: "#EBEBEB",
      color1: "#EBEBEB",
      file: null,
      fileName: "",
      jtData: null,

      uploadfile1: "none",

      fill1: null,
      fileName1: "",
      upFileList: [],
      upFileListName: [],
      showFile: "none",
      changeFileText: "",
      changeFileUp: "none",
      editAddNewFIle: false,
      paixuName: "",
      ifPaixu: null,
      endPickerOptions: {
        disabledDate: (time) => {
          // 默认情况下，结束日期不能早于开始日期
          if (this.issueDate) {
            return time.getTime() < this.issueDate.getTime();
          }
          return false;
        },
      },
      haveChange: false,
    };
  },
  props: [],
  components: {},
  computed: {},
  filters: {},
  methods: {
    sortChange({ prop, order }) {
      this.paixuName = prop;
      this.tableData = [];
      if (order == "descending") {
        this.ifPaixu = false;
        this.getRenderList();
      } else if (order == "ascending") {
        this.ifPaixu = true;
        this.getRenderList();
      } else {
        this.paixuName = null;
        this.getRenderList();
      }
    },
    backToIndex() {
      if (this.showIndex) {
        if (this.addOrEdit == "编辑") {
          let data = {
            name: this.name,
            number: this.number,
            file: this.upFileListName,
            issueDate: this.issueDate,
            visaDate: this.visaDate,
            limitedTerm: this.limitedTerm,
            issuingUnit: this.issuingUnit,
            remark: this.remark,
          };
          let equal = _.isEqual(data, JSON.parse(this.compare));
          if (equal) {
            this.close();
          } else {
            this.$confirm("数据信息有变化是否保存再离开？", "提示", {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              // type: "warning",
            })
              .then(() => {
                this.sureAdd();
              })
              .catch(() => {
                this.close();
              });
          }
        } else if (this.addOrEdit == "新增") {
          this.close();
        }
      } else {
        let data = {
          name: this.name,
          number: this.number,
          file: this.upFileListName,
          issueDate: this.issueDate,
          visaDate: this.visaDate,
          limitedTerm: this.limitedTerm,
          issuingUnit: this.issuingUnit,
          remark: this.remark,
        };
        let equal = _.isEqual(data, JSON.parse(this.compare));
        if (equal) {
          this.$router.push("/app.homePage");
        } else {
          this.$confirm("数据信息有变化是否保存再离开？", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            // type: "warning",
          })
            .then(() => {
              this.sureAdd();
            })
            .catch(() => {
              this.$router.push("/app.homePage");
            });
        }
      }
    },

    backIndexPage() {
      sessionStorage.setItem("backFlag", "true");
      this.$router.push("/app.deviceCertificateSee");
    },
    handleRowClick(row, column, event) {
      // row: 当前行的数据
      // column: 当前点击的列对象
      // event: 原生 DOM 事件对象
      if (row.url.includes(".png") == 1 || row.url.includes(".jpg") == 1) {
        this.rightShowFlag = "png";
      } else if (
        row.url.includes(".pdf") == 1 ||
        row.url.includes(".PDF") == 1
      ) {
        this.rightShowFlag = "pdf";
      }
      this.src = row.url + "?" + new Date().getTime();
      // 在这里执行你的逻辑，例如导航到详情页面、更新数据等
    },
    async clickEdit(a) {
      if (this.showIndex) {
        this.upFileList = [];
        this.upFileListName = [];
        this.addOrEdit = "编辑";
        this.tableData.forEach((item) => {
          if (item.id == a) {
            this.name = item.name;
            this.number = item.number;
            this.remark = item.remark;
            this.file = item.file;
            this.issueDate = item.issueDate;
            this.visaDate = item.visaDate;
            this.limitedTerm = item.limitedTerm;
            this.issuingUnit = item.issuingUnit;
            this.id = a;
            if (item.file && JSON.parse(item.file).length > 0) {
              JSON.parse(item.file).forEach((item) => {
                this.upFileList.push({
                  url: this.$link + "certificate/" + item,
                  name: item,
                });
                this.upFileListName.push(item);
              });
              if (
                this.upFileListName[0].includes(".png") == 1 ||
                this.upFileListName[0].includes(".jpg") == 1
              ) {
                this.rightShowFlag = "png";
                this.src =
                  this.$base +
                  "/download/certificate/" +
                  this.upFileListName[0] +
                  "?" +
                  new Date().getTime();
              } else if (
                this.upFileListName[0].includes(".pdf") == 1 ||
                this.upFileListName[0].includes(".PDF") == 1
              ) {
                this.rightShowFlag = "pdf";
                this.src =
                  this.$base +
                  "/download/certificate/" +
                  this.upFileListName[0] +
                  "?" +
                  new Date().getTime();
              }
            }
            this.compare = JSON.stringify({
              name: item.name,
              number: item.number,
              remark: item.remark,
              file: this.upFileListName,
              issueDate: item.issueDate,
              visaDate: item.visaDate,
              limitedTerm: item.limitedTerm,
              issuingUnit: item.issuingUnit,
            });
          }
          this.show = "block";
        });
      } else {
        this.upFileList = [];
        this.upFileListName = [];
        this.addOrEdit = "编辑";
        await service({
          methods: "get",
          url: `ship-device/${a}`,
        })
          .then((e) => {
            let item = e.data;
            this.name = item.name;
            this.number = item.number;
            this.remark = item.remark;
            this.file = item.file;
            this.issueDate = item.issueDate;
            this.visaDate = item.visaDate;
            this.limitedTerm = item.limitedTerm;
            this.issuingUnit = item.issuingUnit;
            this.id = a;

            if (item.file && JSON.parse(item.file).length > 0) {
              JSON.parse(item.file).forEach((item) => {
                this.upFileList.push({
                  url: this.$link + "certificate/" + item,
                  name: item,
                });
                this.upFileListName.push(item);
              });
              if (
                this.upFileListName[0].includes(".png") == 1 ||
                this.upFileListName[0].includes(".jpg") == 1
              ) {
                this.rightShowFlag = "png";
                this.src =
                  this.$base +
                  "/download/certificate/" +
                  this.upFileListName[0] +
                  "?" +
                  new Date().getTime();
              } else if (
                this.upFileListName[0].includes(".pdf") == 1 ||
                this.upFileListName[0].includes(".PDF") == 1
              ) {
                this.rightShowFlag = "pdf";
                this.src =
                  this.$base +
                  "/download/certificate/" +
                  this.upFileListName[0] +
                  "?" +
                  new Date().getTime();
              }
            }

            this.compare = JSON.stringify({
              name: item.name,
              number: item.number,
              remark: item.remark,
              file: this.upFileListName,
              issueDate: item.issueDate,
              visaDate: item.visaDate,
              limitedTerm: item.limitedTerm,
              issuingUnit: item.issuingUnit,
            });

            this.show = "block";
          })
          .catch((err) => {});
      }
    },
    indexNumber(index) {
      return (this.page - 1) * this.size + index + 1;
    },
    handleStartDateChange() {
      if (
        this.issueDate &&
        this.limitedTerm &&
        this.issueDate > this.limitedTerm
      ) {
        // 如果开始日期晚于结束日期，提示用户并重置结束日期
        this.$message.warning("签发日期不能晚于有效期，已重置有效期");
        this.limitedTerm = null;
      }

      // 更新第二个日期选择器的可选范围
      this.endPickerOptions = {
        disabledDate: (time) => {
          // 结束日期不能早于开始日期
          if (this.issueDate) {
            return time.getTime() < this.issueDate.getTime();
          }
          return false;
        },
      };
      this.haveChange = true;
    },
    // 监听第二个日期选择器的值变化
    handleEndDateChange() {
      if (
        this.issueDate &&
        this.limitedTerm &&
        this.limitedTerm < this.issueDate
      ) {
        // 如果结束日期早于开始日期，提示用户并重置结束日期
        this.$message.warning("有效期不能早于签发日期，已重置有效期");
        this.limitedTerm = null;
      }
      this.haveChange = true;
    },
    handleRowDblclick(row) {
      this.clickEdit(row.id);
    },
    // 跳转页面
    skipPage() {
      if (this.shipPageNumer <= this.totalPages && this.shipPageNumer > 0) {
        this.page = this.shipPageNumer;
        this.getRenderList();
      } else {
        this.$message({
          type: "warning",
          message: "超出页面数量范围",
        });
      }
    },
    // 批量删除开始========================
    selecttableFunction(row) {
      if (row.length > 0) {
        this.multi = [];
        row.forEach((element) => {
          this.multi.push(element.id);
        });
      } else {
        this.multi = [];
      }
    },
    deleteMulti() {
      // let that = this;
      if (this.multi.length == 0) {
        return this.$message({
          type: "warning",
          message: "请先选中再进行批量删除操作！",
        });
      }
      let data = {
        idList: this.multi + "",
      };

      this.$alert("确定删除选中的信息？", {
        confirmButtonText: "确定",
        callback: (action) => {
          if (action == "confirm") {
            service({
              method: "delete",
              url: `/ship-device`,
              params: data,
            }).then((r) => {
              if (r.status == "SUCCESS") {
                this.$message({
                  type: "success",
                  message: "删除成功",
                });
                if (this.currentNum == this.multi.length && this.page > 1) {
                  this.page--;
                }
                this.getRenderList();
              }
            });
          } else {
            this.$message({
              type: "info",
              message: "取消删除",
            });
          }
        },
      });
    },
    //批量删除结束=============================
    showXiQIng(a) {
      if (a) {
        if (JSON.parse(a).length > 0) {
          return "详情";
        } else {
          return "";
        }
      } else {
        return "";
      }
    },
    showDetileFile(a) {
      this.upFileList = [];
      this.upFileListName = [];
      this.showFile = "block";

      JSON.parse(a.file).forEach((item) => {
        this.upFileList.push({
          url: this.$link + "certificate/" + item,
          name: item,
        });
        this.upFileListName.push(item);
      });
    },
    submitAddFile1() {
      if (this.addOrEdit == "编辑" && !this.editAddNewFIle) {
        if (
          (this.changeFileText.includes(".pdf") &&
            (!this.fileName1.includes(".pdf") ||
              !this.fileName1.includes(".PDF"))) ||
          (this.changeFileText.includes(".jpg") &&
            !this.fileName1.includes(".jpg")) ||
          (this.changeFileText.includes(".png") &&
            !this.fileName1.includes(".png"))
        ) {
          return this.$message({
            message: "不同文件类型无法替换，你可以选择新增",
          });
        }
      }

      if (this.file) {
        let data = {
          file: this.file,
          type: 4,
          fileName: this.changeFileText,
        };
        service({
          method: "post",
          url: "/system/upload-file",
          headers: {
            "Content-Type": "multipart/form-data",
          },
          data: data,
        })
          .then((res) => {
            document.getElementById("addfile").value = "";
            this.$message({
              message: "选择成功",
              type: "success",
            });
            this.file1 = "";
            this.changeFileUp = "none";
            this.haveChange = true;
            if (this.editAddNewFIle && this.addOrEdit == "编辑") {
              this.upFileList.push({
                url: this.$link + "certificate/" + res.data,
                name: res.data,
              });
              this.upFileListName.push(res.data);
            } else if (this.addOrEdit == "新增") {
              this.upFileList.push({
                url: this.$link + "certificate/" + res.date,
                name: res.data,
              });
              this.upFileListName.push(res.data);
            }

            if (
              res.data.includes(".png") == 1 ||
              res.data.includes(".jpg") == 1
            ) {
              this.rightShowFlag = "png";
              this.src =
                this.$base +
                "/download/certificate/" +
                res.data +
                "?" +
                new Date().getTime();
            } else if (
              res.data.includes(".pdf") == 1 ||
              res.data.includes(".PDF") == 1
            ) {
              this.rightShowFlag = "pdf";
              this.src =
                this.$base +
                "/download/certificate/" +
                res.data +
                "?" +
                new Date().getTime();
            }

            this.fileName1 = "";
            this.uploadfile1 = "none";
            this.changeFileText = "";
            this.editAddNewFIle = false;
          })
          .catch((err) => {
            document.getElementById("addfile").value = "";
            this.$message({
              message: err,
              type: "fail",
            });
            this.changeFileText = "";
            this.file1 = "";
          });
      } else {
        this.$message({
          message: "请先选择文件再上传",
          type: "warning",
        });
      }
    },

    getFile1() {
      this.file = event.target.files[0];
      this.fileName1 = this.file.name;
      document.getElementsByClassName("addfile4")[0].value = "";
    },
    closeDialog5() {
      this.showFile = "none";
    },
    clickSeeFile(a) {
      const link = document.createElement("a");
      // link.download = "image.png";
      link.href = a;
      link.target = "blank";
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    },
    // 下载图片和pdf
    async clickDownLoadFile(a, b) {
      let that = this;
      let time = this.getFileName();
      this.token = sessionStorage.getItem("token");
      this.token = JSON.parse(this.token);

      let url = this.$loadFile + "/system/download/" + b;

      axios({
        method: "get",
        url: url,
        responseType: "blob", // 关键：设置响应类型为blob
        params: {
          type: 4,
        },
        headers: {
          token: that.token,
        },
      }).then((response) => {
        const url = window.URL.createObjectURL(new Blob([response.data]));
        const link = document.createElement("a");
        link.href = url;
        link.download = time + b;
        // b.toString();
        // if (b.includes(".png") || b.includes(".jpg")) {
        //   link.download = time + b; // 替
        // } else if (b.includes(".pdf") || b.includes(".PDF")) {
        //   link.download = time + b;
        // }
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        window.URL.revokeObjectURL(url);
      });
    },
    // 更改文件
    changeFile(a, b) {
      this.changeFileText = b;
      this.changeFileUp = "block";
    },
    editAddnewFile() {
      this.changeFileUp = "block";
      this.editAddNewFIle = true;
    },
    clickDeleteFile(a, b) {
      let data = {
        type: 4,
        fileName: b,
      };
      this.$alert("确定删除这条信息？", {
        confirmButtonText: "确定",
        callback: (action) => {
          if (action == "confirm") {
            let num = this.upFileListName.indexOf(b);
            this.upFileListName.splice(num, 1);
            this.upFileList.splice(num, 1);
            service({
              method: "delete",
              url: "/system/delete-file",
              params: data,
            })
              .then((e) => {})
              .catch((e) => {});
          } else {
            this.$message({
              type: "info",
              message: "取消删除",
            });
          }
        },
      });
    },

    // 新增加内容部分结束=====================================
    formatDate(row, column) {
      // 获取单元格数据
      let data = row[column.property];

      if (data == null || data == "" || data == undefined) {
        return null;
      }
      let date = new Date(data);
      let year = date.getFullYear();
      let month = date.getMonth() + 1;
      let day = date.getDate();
      return `${year}/${month}/${day}`;
    },
    formatincludeFlag(row, column) {
      // 获取单元格数据
      let data = row[column.property];
      if (data == null) {
        return null;
      }
      if (data == 0) {
        return "否";
      } else if (data == 1) {
        return "是";
      }
    },
    customIndex(index) {
      return (this.page - 1) * this.size + index + 1;
    },
    // 导入文件================
    uploadFile() {
      this.uploadfile = "block";
    },
    getFile(event) {
      this.file = event.target.files[0];
      this.fileName = this.file.name;
    },
    submitAddFile() {
      if (this.file) {
        let data = {
          file: this.file,
          type: this.type,
        };
        service({
          method: "post",
          url: "/ship-device/upload",
          headers: {
            "Content-Type": "multipart/form-data",
          },
          data: data,
        })
          .then((res) => {
            document.getElementsByClassName("addfile")[0].value = "";
            if (res.status == "SUCCESS") {
              this.$message({
                message: "上传成功",
                type: "success",
              });

              this.getRenderList();
            }
            this.file = "";
            this.fileName = "";
            this.uploadfile = "none";
            // else if (res.status == "ERROR") {
            //   this.$message({
            //     message: res.error,
            //     type: "warning",
            //   });
            //   this.file = "";
            //   this.fileName = "";
            //   this.uploadfile = "none";
            //   this.getRenderList();
            // }
          })
          .catch((err) => {
            this.$message({
              message: err,
              type: "fail",
            });
          });
      } else {
        this.$message({
          message: "请先选择文件再上传",
          type: "warning",
        });
      }
    },
    cancelUp() {
      this.file = "";
      this.fileName = "";
      this.uploadfile = "none";
      this.uploadfile1 = "none";
      this.changeFileUp = "none";
      this.fileName1 = "";
      document.getElementsByClassName("addfile1")[0].value = "";
    },
    // 导入文件结束=============

    // 删除数据
    deleteOne(a) {
      // let that = this;
      this.$alert("确定删除这条信息？", {
        confirmButtonText: "确定",
        callback: (action) => {
          if (action == "confirm") {
            service({
              method: "delete",
              url: `/ship-device/${a}`,
            })
              .then((r) => {
                if (r.status == "SUCCESS") {
                  this.$message({
                    type: "success",
                    message: "删除成功",
                  });
                  if (this.showIndex) {
                    if (this.currentNum == 1 && this.page > 1) {
                      this.page--;
                    }
                    this.getRenderList();
                    this.show = "none";
                  } else {
                    this.$router.push("/app.homePage");
                  }
                }
              })
              .catch((err) => {
                this.$message({
                  type: "danger",
                  message: "出错了！",
                });
              });
          } else {
            this.$message({
              type: "info",
              message: "取消删除",
            });
          }
        },
      });
    },
    // 弹窗确认按钮
    sureAdd() {
      this.data.name = this.name;
      this.data.number = this.number;
      this.data.remark = this.remark;
      this.data.file = this.file;
      this.data.issueDate = this.issueDate;
      this.data.visaDate = this.visaDate;
      this.data.limitedTerm = this.limitedTerm;
      this.data.issuingUnit = this.issuingUnit;

      this.data.id = this.id;
      this.data.file = JSON.stringify(this.upFileListName);
      this.data.type = this.type;

      if (this.addOrEdit == "编辑") {
        service({
          method: "put",
          data: this.data,
          url: "/ship-device",
        })
          .then((r) => {
            if (r.status == "SUCCESS") {
              this.$message({
                type: "success",
                message: "修改成功",
              });
              if (this.showIndex) {
                this.getRenderList();
                this.show = "none";
                this.clearCanShu();
              } else {
                this.$router.push("/app.homePage");
              }
            }
          })
          .catch((err) => {
            this.$message({
              type: "info",
              message: "出错了！",
            });
          });
      } else {
        service({
          method: "post",
          data: this.data,
          url: "/ship-device",
        })
          .then((r) => {
            if (r.status == "SUCCESS") {
              this.$message({
                type: "success",
                message: "新增成功",
              });
              this.getRenderList();
              this.show = "none";
              this.clearCanShu();
            }
          })
          .catch((err) => {
            this.$message({
              type: "info",
              message: "出错了！",
            });
          });
      }
    },
    reduceDate(a) {
      let date = new Date(a);
      let year = date.getFullYear();
      let month = date.getMonth() + 1;
      let day = date.getDate();
      return `${year}-${month}-${day}`;
    },
    // 关闭弹窗
    close() {
      this.show = "none";
      this.show1 = "none";
      this.clearCanShu();
      this.uploadfile = "none";
      this.uploadfile1 = "none";
      this.changeFileUp = "none";
    },
    // 新增
    addOne() {
      this.addOrEdit = "新增";
      // this.$refs["dialog"].style.display = show;
      this.show = "block";
    },
    // 导出文件
    getFileName() {
      let date = new Date();
      let year = date.getFullYear().toString();
      let month =
        date.getMonth() + 1 > 9
          ? date.getMonth() + 1
          : "0" + (date.getMonth() + 1);
      let day =
        date.getDate() > 10 ? date.getDate().toString() : "0" + date.getDate();
      let hour =
        date.getHours() > 10
          ? date.getHours().toString()
          : "0" + date.getHours();
      let min =
        date.getMinutes() > 10
          ? date.getMinutes().toString()
          : "0" + date.getMinutes();
      date = null;
      return `${year}${month}${day}${hour}${min}`;
    },
    async getExcelFile() {
      let that = this;
      let time = this.getFileName();
      this.token = sessionStorage.getItem("token");
      this.token = JSON.parse(this.token);
      axios({
        method: "get",
        url: this.$loadFile + "/ship-device/export",
        responseType: "blob", // 关键：设置响应类型为blob
        data: {
          fileName: "设备证书",
        },
        params: {
          type: this.type,
        },
        headers: {
          token: that.token,
        },
      })
        .then((response) => {
          const url = window.URL.createObjectURL(new Blob([response.data]));
          // 创建一个隐藏的<a>标签，并设置其href属性为上面创建的URL
          const link = document.createElement("a");
          link.href = url;
          link.download = "设备证书-" + time + ".xls"; // 替

          document.body.appendChild(link);

          link.click();

          document.body.removeChild(link);

          window.URL.revokeObjectURL(url);
        })
        .catch((error) => {
          this.$message({
            message: "文件下载失败",
            type: "info",
          });
        });
    },
    sendMessage() {
      let res = rename();
      EventBus.emit("custom-event", res);
    },
    // 获取列表数据
    async getRenderList() {
      let data = {};
      if (!this.searchName && !this.paixuName) {
        data = {
          page: this.page,
          size: this.size,
          type: this.type,
        };
      } else if (this.searchName && !this.paixuName) {
        data = {
          page: this.page,
          size: this.size,
          type: this.type,
          name: this.searchName,
        };
      } else if (!this.searchName && this.paixuName) {
        data = {
          page: this.page,
          size: this.size,
          type: this.type,
          sortStr: this.paixuName,
          isDesc: this.ifPaixu,
        };
      } else if (this.searchName && this.paixuName) {
        data = {
          page: this.page,
          size: this.size,
          type: this.type,
          sortStr: this.paixuName,
          isDesc: this.ifPaixu,
          name: this.searchName,
        };
      }

      await service({
        methods: "get",
        url: "/ship-device/find-one-page",
        params: data,
      })
        .then((e) => {
          this.totalPages = e.data.totalPages;
          this.totalNumber = e.data.totalElements;
          if (this.totalPages == 0) {
            this.totalPages = 1;
          }
          if (this.page < this.totalPages) {
            this.color1 = "#268FDE";
          } else {
            this.color1 = "#EBEBEB";
          }
          if (this.page == 1) {
            this.color = "#EBEBEB";
          } else {
            this.color = "#268FDE";
          }
          this.tableData = e.data.content;
          this.currentNum = e.data.numberOfElements;
        })
        .catch((err) => {});
    },
    formatterDate(a) {
      let date = new Date(a);
      let year = date.getFullYear();
      let month = date.getMonth() + 1;
      let day = date.getDate();
      return `${year}/${month}/${day}`;
    },
    clearCanShu() {
      this.name = "";
      this.number = "";
      this.remark = "";
      this.file = "";
      this.issueDate = "";
      this.visaDate = "";
      this.limitedTerm = "";
      this.issuingUnit = "";
      this.upFileList = [];
      this.upFileListName = [];

      this.id = "";
      this.src = "";
      this.haveChange = false;
      this.data = {
        name: "",
        number: "",
        remark: "",
        file: "",
        issueDate: "",
        visaDate: "",
        limitedTerm: "",
        issuingUnit: "",
        type: this.type,
        id: "",
      };
    },

    clickLastPage() {
      if (this.page > 1) {
        this.page--;
        if (this.page == 1) {
          this.color = "#EBEBEB";
        } else {
          this.color = "#268FDE";
        }
        if (this.page < this.totalPages) {
          this.color1 = "#268FDE";
        }
        this.getRenderList();
      } else {
        this.color = "#EBEBEB";
      }
    },
    handSize() {
      if (window.innerWidth > 630) {
        if (this.$store.state.width == 200) {
          this.tableWidth = (window.innerWidth - 170) * 0.985 - 20 + "px";
        } else if (this.$store.state.width == 90) {
          this.tableWidth = (window.innerWidth - 60) * 0.985 - 20 + "px";
        }
      } else {
        this.tableWidth = window.innerWidth - 30 + "px";
      }
    },
    clickNextPage() {
      if (this.page < this.totalPages) {
        this.page++;
        this.color = "#268FDE";
        if (this.page == this.totalPages) {
          this.color1 = "#EBEBEB";
        } else {
          this.color1 = "#268FDE";
        }
      }
      this.getRenderList();
    },
  },
  watch: {
    "$store.state.width"(newVal, oldVal) {
      //对数据执行操作
      if (window.innerWidth > 630) {
        if (newVal == 90) {
          this.tableWidth = (window.innerWidth - 60) * 0.985 - 20 + "px";
        } else if (newVal == 200) {
          this.tableWidth = (window.innerWidth - 170) * 0.985 - 20 + "px";
        }
      }
    },
    upFileList: function () {
      this.$nextTick(function () {
        this.$refs.leftTable.setCurrentRow(this.upFileList[0]);
      });
    },
  },

  created() {
    this.sendMessage();
    this.type = this.$route.query.id;
    this.shipDetailType = this.$route.query.name;
    try {
      if (this.$route.query.type) {
        this.showIndex = false;
        this.addOrEdit = "编辑";
        this.clickEdit(this.$route.query.dataId);
      }
    } catch (error) {}
  },
  beforeMount() {
    if (window.innerWidth > 630) {
      if (this.$store.state.width == 200) {
        this.tableWidth = (window.innerWidth - 170) * 0.985 - 20 + "px";
      } else if (this.$store.state.width == 90) {
        this.tableWidth = (window.innerWidth - 60) * 0.985 - 20 + "px";
      }
    } else {
      this.tableWidth = window.innerWidth - 30 + "px";
    }
  },
  mounted() {
    let that = this;
    this.getRenderList();

    // this.sendMessage();
    window.addEventListener("resize", this.handSize);
  },
  beforeUnmount() {
    window.removeEventListener("resize", this.handSize);
  },
};
</script>
<style lang="less" scoped>
.fileName {
  font-size: 15px;
  color: black;
  height: 3vh;
  line-height: 3vh;
  width: 100%;
  text-align: center;
}

.manyInput {
  width: 1540px;
  height: 80vh;
  display: flex;
  justify-content: center;
  margin: auto;
  overflow-x: auto;

  .iuptInnerContain {
    width: 620px;
    // width: 100%;
    height: 400px;
    display: flex;
    flex-wrap: wrap;

    .inputInner {
      width: 295px;
      min-height: 35px;
      margin-top: 10px;
      margin-right: 10px;
      display: flex;
      align-items: center;
      position: relative;
      color: #365488;
      .name {
        width: 70px;
        height: 100%;
        line-height: 4vh;
        text-align: right;
        font-size: 15px;
      }
      // .name1 {
      //   width: 210px;
      //   margin-left: 10px;
      //   display: flex;
      //   align-items: center;
      //   justify-content: baseline;
      //   min-height: 3vh;
      //   text-indent: 1em;
      //   outline: none;
      //   font-size: 15px;
      //   border: none;
      //   background: #ebebeb;
      //   color: #365488;
      // }
      .inputContainer {
        width: 210px;
        margin-left: 5px;
      }
      .el-input__inner {
        background: white !important;
      }
      input {
        width: 220px;
        height: 34px;
        margin-left: 5px;
        border-radius: 5px;
        text-indent: 1em;
        outline: none;
        border: none;
        background: white !important;
        color: #365488;
        border: 1px solid #dcdfe6;
      }
      input::-webkit-input-placeholder {
        color: #a8abb2;
      }
      input[type="date"] {
        // padding: 5px;
        color: #365488;
        text-align: left;
        // border: 1px solid #365488;
        border-radius: 4px;
        // background-color: #fff;
        box-sizing: border-box; /* 确保内边距和边框不会影响元素的总宽度 */
      }
    }
    .el-date-picker .el-picker-panel {
      background-color: white !important; /* 你想要的背景颜色 */
    }
  }
}
.dialogText {
  margin: auto;
  width: 50%;
  line-height: 4vh;
  font-size: 25px;
  color: black;
  // text-indent: 10px;
  text-align: center;
  // font-size: 20px;
  font-weight: 800;
}

.dialog,
.dialog1 {
  width: 100%;
  height: 100%;
  background: #dfe6e8;
  position: absolute;
  top: 0;
  left: 0;
  display: none;
  z-index: 100;
}
.loadHomeWork {
  overflow: hidden;
  width: 100%;
  height: 100%;
  position: relative;
  .loadHomeWorkIneer {
    width: 98.5%;
    height: 91vh;
    margin: auto;
    margin-top: 1vh;
    overflow: auto;
    background: white;

    .loadSecond {
      width: 280px;

      color: black;
      text-align: center;
      line-height: 33px;
      color: black;
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin-left: 10px;
      font-size: 15px;
      .topName {
        width: 90px;
        line-height: 33px;
        background: #67c23a;
        border-radius: 5px;
        a {
          display: block;
          width: 90px;
          line-height: 33px;
          text-decoration: none;
          color: white;
        }
      }
      .topName:nth-child(3) {
        background: #242121;
      }
    }
  }
  // background: blue;
}
.table {
  width: 98.5%;
  margin: auto;
  // margin-top: 2vh;
  height: 65vh;
  // background: red;
}

@media (min-width: 0px) and (max-width: 960px) {
  .manyInput {
    width: 375px !important;
    display: block !important;
    .inputInner {
      margin: auto !important;
      // margin-top: 10px !important;
    }
  }
  .closeAndSrue {
    width: 110px;
  }
}
</style>
